package com.threeti.mecool.web.controller.report;

import static com.threeti.mecool.core.domain.model.basicdata.biz.MeCoolAdminDivisionAreaRegistry.customAreaRegistry;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.application.basicdata.BasicDataService;
import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.application.report.ReportService;
import com.threeti.mecool.core.application.report.StoreOpeningRate;
import com.threeti.mecool.core.application.report.StoreOpeningRateReportCriteria;
import com.threeti.mecool.core.domain.model.basicdata.AdminDivisionLevelDeep;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultRepository;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.legacy.domain.model.basicdata.AdminDivisionLegacy;
import com.threeti.mecool.legacy.infrastructure.persistence.AdminDivisionLegacyRepository;
import com.threeti.mecool.legacy.infrastructure.persistence.PosSysTypeLegacyRepository;
import com.threeti.mecool.web.util.RequestUtil;

@Controller
@RequestMapping("/report/storeOpeningRate")
public class StoreOpeningRateReportController {

	public static final Logger logger = LoggerFactory.getLogger(StoreOpeningRateReportController.class);

	@Autowired
	private PlanJobResultRepository planJobResultRepo;

	@Autowired
	private ReportService rptService;

	@Autowired
	private AdminDivisionLegacyRepository adminDivLegRepo;

	@Autowired
	private AdminDivisionLegacyRepository adminDivisionLegacyRepository;

	@Autowired
	private PosSysTypeLegacyRepository posSysTypeLegacyRepository;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private BasicDataService basicDataService;
	
	@SuppressWarnings("unchecked")
	private void basicData(Map modelMap){
		modelMap.put("provinceList",adminDivisionLegacyRepository.findByDeep(1));
		modelMap.put("sysPosKindList", posSysTypeLegacyRepository.findAll());
		
		modelMap.put("projectList", projectService.findProjectBasicInfoByUserPermission(userService.getUserFromSession()));
		modelMap.put("posKindList", basicDataService.findAllPosKindListByTreeFormat());
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			modelMap.put("customArea",mapper.writeValueAsString(customAreaRegistry()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/openRateReport.html")
	public void openRateReport(Map modelMap) {
		basicData(modelMap);
	}
	
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportList/{adminDivLevelDeep}.html")
	public String reportList(@PathVariable int adminDivLevelDeep, Map modelMap,HttpServletRequest request) {
		modelMap.putAll(RequestUtil.getParameterMap(request));
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
		return "/report/storeOpeningRate/reportList";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportList/6/{customAdminDivAreaCode}.html")
	public String reportList1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		modelMap.putAll(RequestUtil.getParameterMap(request));
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);

		return "/report/storeOpeningRate/reportList";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportList/1/{standardAdminDivAreaCode}.html")
	public String reportList2(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		// TODO
		Map<String, String> parameterMap = RequestUtil.getParameterMap(request);
		
		//丑陋
		if (standardAdminDivAreaCode.equals("11000000") || standardAdminDivAreaCode.equals("12000000") || standardAdminDivAreaCode.equals("31000000") || standardAdminDivAreaCode.equals("50000000")) {
			return reportList3(standardAdminDivAreaCode, modelMap, request);
		}

		// 将异步操作转化为同步操作以满足地图绘制...
		List<StoreOpeningRate> rates = rptService.storeOpeningRateSummaryByProvince(standardAdminDivAreaCode,StoreOpeningRateReportCriteria.newCriteria(parameterMap));
		modelMap.put("storeOpeningRates", rates);
		
		AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
		String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentProvinceAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentProvinceAdName();
		modelMap.put("standardAdminDivAreaName", provinceAdName);
		
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.CITY.ordinal());
		modelMap.put("mapZoomLevel", "8");// 8是一个相对合适的用于省市级别展示的ZOOM等级
		
		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);
		return "/report/storeOpeningRate/reportListCityMap";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportList/2/{standardAdminDivAreaCode}.html")
	public String reportList3(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		Map<String, String> parameterMap = RequestUtil.getParameterMap(request);
		
		List<StoreOpeningRate> rates = rptService.storeOpeningRateSummaryByCity(standardAdminDivAreaCode, 
																				StoreOpeningRateReportCriteria.newCriteria(parameterMap));
		// TODO
		try {
			String pageSize = parameterMap.get("pageSize");
			int pointSize=0;
			try {
				pointSize=Integer.valueOf(pageSize);
			} catch (Exception e) {
				pointSize=100;
				parameterMap.put("pageSize", String.valueOf(pointSize));
			}
			
			List<Map<String, Object>> planOpenStoreList = rptService.getPlannedOpenStoresListByCity(userService.getUserFromSession(),pointSize, standardAdminDivAreaCode, parameterMap.get("projectCode"));
			List<Map<String, Object>> actualOpenStoreList=Lists.newArrayList();
			
			List<String> channelIdList=Lists.newArrayList();
			for (Map<String, Object> map : planOpenStoreList) {
				channelIdList.add(map.get("id").toString());
			}
			if(planOpenStoreList.size()>0){
				List<Object[]> openIdList=planJobResultRepo.findChannelByChannelId(channelIdList);
				for (Object[] row : openIdList) {
					for (Map<String, Object> map : planOpenStoreList) {
						if(map.get("id").toString().equals(row[0].toString())){
							map.put("FINISH_AT", row[1]);
							actualOpenStoreList.add(map);
							planOpenStoreList.remove(map);
							break;
						}
					}
				}
			}
			
			// 计划门店和实际门店均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
			AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
			String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentCityAdName();
			modelMap.put("standardAdminDivAreaName", provinceAdName);
			
			// 明细数据
			modelMap.put("actualStoresDetail", new ObjectMapper().writeValueAsString(actualOpenStoreList));
			modelMap.put("plannedStoresDetail", new ObjectMapper().writeValueAsString(planOpenStoreList)); //plannedStoresDetail
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		modelMap.putAll(parameterMap);
		modelMap.put("storeOpeningRates", rates);// 汇总数据
		modelMap.put("mapZoomLevel", "10");// 13是一个相对合适的用于城区级别展示的ZOOM等级
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);

		return "/report/storeOpeningRate/reportListCityMap";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportListData/{adminDivLevelDeep}.html")
	public String reportListData(@PathVariable int adminDivLevelDeep,Map modelMap,HttpServletRequest request) {
		
		
		// TODO
		List<StoreOpeningRate> rates = Lists.newArrayList();
		if (adminDivLevelDeep == AdminDivisionLevelDeep.NATIONWIDE.ordinal()) {
			rates.add(rptService.storeOpeningRateSummaryByCountry(StoreOpeningRateReportCriteria.newCriteria(RequestUtil.getParameterMap(request))));
		} else if (adminDivLevelDeep == AdminDivisionLevelDeep.PROVINCE.ordinal()) {
			rates = rptService.storeOpeningRateSummaryByProvinceALL(StoreOpeningRateReportCriteria.newCriteria(RequestUtil.getParameterMap(request)));
			modelMap.put("storeOpeningRatesNationwide",rptService.storeOpeningRateSummaryByCountry(StoreOpeningRateReportCriteria.newCriteria(RequestUtil.getParameterMap(request))));
		} else if (adminDivLevelDeep == AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal()) {
			rates = rptService.storeOpeningRateSummaryByCustomAreas(StoreOpeningRateReportCriteria.newCriteria(RequestUtil.getParameterMap(request)));
		}
		modelMap.put("storeOpeningRates", rates);
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
		
		modelMap.putAll(RequestUtil.getParameterMap(request));

		return "/report/storeOpeningRate/reportListData";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/reportListData/6/{customAdminDivAreaCode}.html")
	public String reportListData1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		
		List<StoreOpeningRate> rates = rptService.storeOpeningRateSummaryByCustomArea(customAdminDivAreaCode,StoreOpeningRateReportCriteria.newCriteria(RequestUtil.getParameterMap(request)));
		// TODO
		modelMap.put("storeOpeningRates", rates);
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.PROVINCE.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);
		
		modelMap.putAll(RequestUtil.getParameterMap(request));
		
		return "/report/storeOpeningRate/reportListData";
	}
	
}
